//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package data_anno_dao

import (
	"context"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"atomgit.com/openlinksaas/proto-gen-go.git/data_anno_project_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type BaseAnnoProjectInfoDbItem struct {
	Name     string `bson:"name"`     //后续废弃
	AnnoType uint32 `bson:"annoType"` //后续废弃
	Desc     string `bson:"desc"`
	Config   string `bson:"configData"`
}

type AnnoProjectInfoDbItem struct {
	AnnoProjectId string                    `bson:"_id"`
	ProjectId     string                    `bson:"projectId"`
	BaseInfo      BaseAnnoProjectInfoDbItem `bson:"baseInfo"`
	ResourceCount uint32                    `bson:"resourceCount"`
	AllTaskCount  uint32                    `bson:"allTaskCount"`
	DoneTaskCount uint32                    `bson:"doneTaskCount"`
	MemberCount   uint32                    `bson:"memberCount"`
	CreateTime    int64                     `bson:"createTime"`   //后续废弃
	CreateUserId  string                    `bson:"createUserId"` //后续废弃
	UpdateTime    int64                     `bson:"updateTime"`   //后续废弃
	UpdateUserId  string                    `bson:"updateUserId"` //后续废弃
}

func (item *AnnoProjectInfoDbItem) ToAnnoProjectInfo() *data_anno_project_api.AnnoProjectInfo {
	return &data_anno_project_api.AnnoProjectInfo{
		AnnoProjectId: item.AnnoProjectId,
		BaseInfo: &data_anno_project_api.BaseAnnoProjectInfo{
			Desc:   item.BaseInfo.Desc,
			Config: item.BaseInfo.Config,
		},
		ResourceCount: item.ResourceCount,
		AllTaskCount:  item.AllTaskCount,
		DoneTaskCount: item.DoneTaskCount,
		MemberCount:   item.MemberCount,
	}
}

type _AnnoProjectDao struct {
	mc *mongo.Collection
}

func newAnnoProjectDao(db *mongo.Database) (*_AnnoProjectDao, error) {
	mc := db.Collection(db_ns.DB_NS_DATA_ANNO + "project")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"projectId", 1}, {"createTime", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_AnnoProjectDao{mc: mc}, nil
}

func (db *_AnnoProjectDao) Insert(ctx context.Context, dbItem *AnnoProjectInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_AnnoProjectDao) Count(ctx context.Context, projectId string) (uint32, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"projectId": projectId})
	return uint32(count), err
}

func (db *_AnnoProjectDao) List(ctx context.Context, projectId string, filterByWatch bool, watchAnnoProjectIdList []string, offset, limit int64) ([]*AnnoProjectInfoDbItem, error) {
	query := bson.M{"projectId": projectId}
	if filterByWatch {
		query["_id"] = bson.M{"$in": watchAnnoProjectIdList}
	}
	cursor, err := db.mc.Find(ctx, query, options.Find().SetSkip(offset).SetLimit(limit).SetSort(bson.M{"createTime": -1}))
	if err != nil {
		return nil, err
	}
	retList := []*AnnoProjectInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_AnnoProjectDao) ListAllForUpgrade(ctx context.Context) ([]*AnnoProjectInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{})
	if err != nil {
		return nil, err
	}
	retList := []*AnnoProjectInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_AnnoProjectDao) ListById(ctx context.Context, projectId string, annoProjectIdList []string, offset, limit int64) ([]*AnnoProjectInfoDbItem, error) {
	if len(annoProjectIdList) == 0 {
		return []*AnnoProjectInfoDbItem{}, nil
	}
	cursor, err := db.mc.Find(ctx, bson.M{"projectId": projectId, "_id": bson.M{"$in": annoProjectIdList}},
		options.Find().SetSkip(offset).SetLimit(limit).SetSort(bson.M{"createTime": -1}))
	if err != nil {
		return nil, err
	}
	retList := []*AnnoProjectInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_AnnoProjectDao) DistinctAnnoProjectIdByProject(ctx context.Context, projectId string) ([]string, error) {
	itemList, err := db.mc.Distinct(ctx, "_id", bson.M{"projectId": projectId})
	if err != nil {
		return nil, err
	}
	retList := []string{}
	for _, item := range itemList {
		retList = append(retList, item.(string))
	}
	return retList, nil
}

func (db *_AnnoProjectDao) Get(ctx context.Context, projectId, annoProjectId string) (*AnnoProjectInfoDbItem, error) {
	retItem := &AnnoProjectInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": annoProjectId, "projectId": projectId}).Decode(retItem)
	return retItem, err
}

func (db *_AnnoProjectDao) Exist(ctx context.Context, projectId, annoProjectId string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": annoProjectId, "projectId": projectId})
	return count > 0, err
}

func (db *_AnnoProjectDao) Remove(ctx context.Context, projectId, annoProjectId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": annoProjectId, "projectId": projectId})
	return err
}

func (db *_AnnoProjectDao) Update(ctx context.Context, projectId, annoProjectId string, dbItem *BaseAnnoProjectInfoDbItem, updateUserId string, updateTime int64) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": annoProjectId, "projectId": projectId}, bson.M{"$set": bson.M{
		"baseInfo":     dbItem,
		"updateTime":   updateTime,
		"updateUserId": updateUserId,
	}})
	return err
}

func (db *_AnnoProjectDao) UpdateResourceCount(ctx context.Context, projectId, annoProjectId string, count uint32) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": annoProjectId, "projectId": projectId}, bson.M{"$set": bson.M{"resourceCount": count}})
	return err
}

func (db *_AnnoProjectDao) UpdateAllTaskCount(ctx context.Context, projectId, annoProjectId string, count uint32) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": annoProjectId, "projectId": projectId}, bson.M{"$set": bson.M{"allTaskCount": count}})
	return err
}

func (db *_AnnoProjectDao) UpdateDoneTaskCount(ctx context.Context, projectId, annoProjectId string, count uint32) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": annoProjectId, "projectId": projectId}, bson.M{"$set": bson.M{"doneTaskCount": count}})
	return err
}

func (db *_AnnoProjectDao) UpdateMemberCount(ctx context.Context, projectId, annoProjectId string, count uint32) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": annoProjectId, "projectId": projectId}, bson.M{"$set": bson.M{"memberCount": count}})
	return err
}
